package top.lingkang.springboothibernate.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

@Configurable
@Component
public class HibernateToConfig {

    @Resource
    private DataSource dataSource;

    /**
     * 此处bean为根据 hibernate 官网配置文件 hibernate.cfg.xml 改造的
     * https://docs.jboss.org/hibernate/orm/5.5/quickstart/html_single/hibernate-tutorials.zip
     *
     * @return
     */
    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
        bean.setDataSource(dataSource);
        // 扫描实体类
        bean.setPackagesToScan("top.lingkang.springboothibernate.entity");
        Properties properties = new Properties();
        properties.setProperty("current_session_context_class", "thread");
        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
        properties.setProperty("connection.pool_size", String.valueOf(druidDataSource.getMaxActive()));
        // 配置方言 mysql 5.7.34
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL57Dialect");
        //        <!-- 控制台打印SQL -->
        properties.setProperty("hibernate.show_sql", "true");
        // 制台打印SQL格式化
        // properties.setProperty("hibernate.format_sql", "true");
        /**
         * create：表示启动的时候先drop，再create
         * create-drop: 也表示创建，只不过再系统关闭前执行一下drop
         * update: 这个操作启动的时候会去检查schema是否一致，如果不一致会做scheme更新
         * validate: 启动时验证现有schema与你配置的hibernate是否一致，如果不一致就抛出异常，并不做更新
         */
        // 首次启动使用 create 让bean自动生成表，之后使用 update 模式即可
        properties.setProperty("hibernate.hbm2ddl.auto", "update");

        bean.setHibernateProperties(properties);
        return bean;
    }

}
